﻿#region
using System;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text.RegularExpressions;
using Google.GData.Client;
using Google.GData.YouTube;
using Google.YouTube;
using YoutubeExtractor;

#endregion

namespace Y2M.Components
{
    public class YoutubeHelper
    {
        private const string key = "AI39si4QWBbUZTl_SCt_lPg_mAWrPmmyHGf_HBz3B00Ke0eGMFnz_s-rD5OMGSRMDskV3YDEvVaPK4zyzPQZd0Q3S_saB531_g";

        public static ClipList Search(string keyword, int startIndex, int numberToRetrieve, out int totalCount)
        {
            YouTubeRequestSettings settings = new YouTubeRequestSettings("Castpia", key);
            YouTubeRequest request = new YouTubeRequest(settings);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = keyword;
            query.SafeSearch = YouTubeQuery.SafeSearchValues.None;
            query.StartIndex = startIndex;
            query.NumberToRetrieve = numberToRetrieve;

            Feed<Video> videoFeed = request.Get<Video>(query);

            totalCount = videoFeed.TotalResults;

            ClipList list = new ClipList(totalCount, startIndex);
            foreach (Video video in videoFeed.Entries)
            {
                Clip clip = new Clip(video);
                list.Add(clip);
            }

            return list;
        }

        public static ClipInfo GetClipInfoFromUrl(string url)
        {
            try
            {
                string videoId = GetVideoId(url);

                if (videoId == null)
                    return null;

                YouTubeRequestSettings settings = new YouTubeRequestSettings("Castpia", key);
                YouTubeRequest request = new YouTubeRequest(settings);

                string entryUrl = "http://gdata.youtube.com/feeds/api/videos/" + videoId;
                Video video = request.Retrieve<Video>(new Uri(entryUrl));

                if (video == null)
                    return null;

                return GetClipInfoFromClip(new Clip(video));
            }
            catch
            {
                return null;
            }
        }

        public static ClipInfo GetClipInfoFromClip(Clip clip)
        {
            var clipInfoList = (from x in DownloadUrlResolver.GetDownloadUrls(clip.WatchPage.ToString())
                                where x.VideoType == VideoType.Mp4 || x.VideoType == VideoType.Flash
                                select new ClipInfo(x, clip)).ToList();
            clipInfoList.Sort(new ClipInfoComparer());

            return clipInfoList.Count > 0 ? clipInfoList[0] : null;
        }

        public static string GetVideoId(string url)
        {
            Match match = Regex.Match(url, @"youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);

            return match.Success ? match.Groups[1].Value : null;
        }
    }
}